package com.zhihuishu.treenity.controller.course;


import com.zhihuishu.micro.course.openapi.course.CCDataOpenService;
import com.zhihuishu.micro.course.openapi.course.dto.CCDataDto;
import com.zhihuishu.micro.course.openapi.course.dto.CCDataFolderMapDto;
import com.zhihuishu.micro.course.openapi.course.dto.CCDataMovieDto;
import com.zhihuishu.remote.RemoteException;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.treenity.controller.BaseController;
import com.zhihuishu.treenity.log.LoggerCollectionEnum;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/***
 * @author jiangli
 *
 */
@Controller
@RequestMapping("/course/thirdStep/file")
public class ThirdStepFileController extends BaseController {
    private static final String MODULE_NAME_CN = "文件";
    private static final String MODULE_NAME_EN = "treenity_step3_file";

    @Resource
    private CCDataOpenService treenityCCDataVideoOpenService;


    @Override
    protected LoggerCollectionEnum getCollectionEnum() {
        return LoggerCollectionEnum.thirdStepFileCollection;
    }


    @ResponseBody
    @RequestMapping("/map")
    public RemoteResult<CCDataFolderMapDto> chapterList(final String foldIds) {
        String[] split = foldIds.split(",");
        final List<Long> lList = new ArrayList<Long>(split.length);
        try {
            for (String ls : split) {
                lList.add(Long.parseLong(ls.trim()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        RemoteResult<CCDataFolderMapDto> listRemoteResult = new ResultRequestAndParser<CCDataFolderMapDto>(MODULE_NAME_CN, MODULE_NAME_EN, "查询", "query") {
            @Override
            public RemoteResult request(Long curUserId) throws RemoteException {
                RemoteResult<CCDataFolderMapDto> rs = treenityCCDataVideoOpenService.queryMapByFolderId(lList);
                return rs;
            }
        }.get();
        return listRemoteResult;
    }


    @ResponseBody
    @RequestMapping("/create")
    public RemoteResult<CCDataDto> chapterCreate(final CCDataDto courseFolderDto) {
        RemoteResult<CCDataDto> result = new ResultRequestAndParser<CCDataDto>(MODULE_NAME_CN, MODULE_NAME_EN, "创建", "create") {
            @Override
            public RemoteResult request(Long curUserId) throws RemoteException {
                RemoteResult<CCDataDto> rs = treenityCCDataVideoOpenService.createByDto(courseFolderDto, curUserId);
                return rs;
            }
        }.get();
        return result;
    }

    //
    @ResponseBody
    @RequestMapping(value = "/delete", method = {RequestMethod.POST, RequestMethod.GET})
    public RemoteResult<Void> chapterDelete(@RequestParam(value = "fileIds[]", required = false) final List<Integer> fileIds) {
        RemoteResult<Void> result = new ResultRequestAndParser<Void>(MODULE_NAME_CN, MODULE_NAME_EN, "删除", "delete") {
            @Override
            public RemoteResult request(Long curUserId) throws RemoteException {
                RemoteResult<Void> rs = treenityCCDataVideoOpenService.deleteByIds(fileIds, curUserId);
                return rs;
            }
        }.get();
        return result;
    }

    //
    @ResponseBody
    @RequestMapping("/update")
    public RemoteResult<CCDataDto> chapterUpdate(final CCDataDto dto) {
        RemoteResult<CCDataDto> result = new ResultRequestAndParser<CCDataDto>(MODULE_NAME_CN, MODULE_NAME_EN, "更新", "update") {
            @Override
            public RemoteResult request(Long curUserId) throws RemoteException {
                RemoteResult<CCDataDto> rs = treenityCCDataVideoOpenService.updateAndGetByDto(dto, curUserId);
                return rs;
            }
        }.get();
        return result;
    }

    @ResponseBody
    @RequestMapping("/updateMulti")
    public RemoteResult<List<CCDataDto>> updateMulti(@RequestParam(value = "fileIds[]", required = false) final List<Integer> fileIds, Long folderId, Integer privilege) {
        final List<CCDataDto> list = new ArrayList<CCDataDto>(fileIds.size());
        for (Integer fileId : fileIds) {
            CCDataDto one = new CCDataDto();
            one.setId(fileId);
            one.setFolderId(folderId);
            one.setPrivilege(privilege);
            list.add(one);
        }

        RemoteResult<List<CCDataDto>> result = new ResultRequestAndParser<List<CCDataDto>>(MODULE_NAME_CN, MODULE_NAME_EN, "批量更新", "updateMulti") {
            @Override
            public RemoteResult request(Long curUserId) throws RemoteException {
                RemoteResult<List<CCDataDto>> rs = treenityCCDataVideoOpenService.updateByDtoList(list, curUserId);
                return rs;
            }
        }.get();
        return result;
    }

    //查询课程下所有视频信息
    @ResponseBody
    @RequestMapping("/videos")
    public RemoteResult<List<CCDataMovieDto>> videos(final Long courseId) {
        RemoteResult<List<CCDataMovieDto>> result = new ResultRequestAndParser<List<CCDataMovieDto>>(MODULE_NAME_CN, MODULE_NAME_EN, "查询视频", "queryVideo") {
            @Override
            public RemoteResult request(Long curUserId) throws RemoteException {
                RemoteResult<List<CCDataMovieDto>> rs = treenityCCDataVideoOpenService.listMovieData(courseId);
                return rs;
            }
        }.get();
        return result;
    }

    @RequestMapping("/download")
    public void downloadPic(final String url, HttpServletRequest request, HttpServletResponse response) {
        log.debug("downloading...{}", url);

//        String displayName = "asd打算犯法的事asd.jpg";
        String displayName = url.substring(url.lastIndexOf("/")+1);


        //文字转码
        try {
            String userAgent = request.getHeader("User-Agent");
            boolean isIE = (userAgent != null) && (userAgent.toLowerCase().indexOf("msie") != -1);
            if (isIE) {
                displayName = URLEncoder.encode(displayName, "UTF-8");
                displayName = "\"" + displayName + "\"";
            } else {
                displayName = new String(displayName.getBytes("UTF-8"), "ISO8859-1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        response.setContentType("image/*;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + displayName);

        //传输
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            // 构造URL
            URL uRL = new URL(url);
            // 打开连接
            URLConnection con = uRL.openConnection();
            //设置请求超时为10s
            con.setConnectTimeout(10*1000);

            // 输入流
            InputStream is = con.getInputStream();
            os = new BufferedOutputStream(response.getOutputStream());
            bis = new BufferedInputStream(is);
            FileCopyUtils.copy(bis, os);
            //IOUtils.copy(is, os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(bis != null)
                    bis.close();
                if(os != null)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
